# -*- coding: utf-8 -*-
# !/usr/bin/env python
import os
import threading
import uuid

from rest_framework.views import APIView
from components.kubernetes.deployments.dao import get_kubernetes_cluster_sign_info, quit_k8s_download_cmd
from components.kubernetes.ssh_exec import SshExec
from general.deploy.dao import download_event_in
from main import settings
from utils.Conf import Configuration
from utils.views import Result, ReturnClass

class DownloadImage(APIView):
    def post(self, request):
        data = request.data
        now_kubernetes_cluster_id = data['now_kubernetes_cluster_id']
        old_kubernetes_cluster_id = data['old_kubernetes_cluster_id']
        if_target_location = data['if_target_location']
        host_info_old = ""

        if not now_kubernetes_cluster_id:
            return Result.fail_response(msg="请选择环境与空间！")
        if not data['data']:
            return Result.fail_response(msg="请选择勾选需要打包的镜像！")

        get_ready_images_list = []
        for image_info in  data['data']:
            if data['if_difference']:
                if image_info['old_version_pod_image'] != image_info['now_version_pod_image']:
                    get_ready_images_list.append(image_info['now_version_pod_image'])
                continue
            get_ready_images_list.append(image_info['now_version_pod_image'])

        #获取主机连接信息
        host_info_ = get_kubernetes_cluster_sign_info(now_kubernetes_cluster_id)
        #获取是否成功
        if not ReturnClass.if_ok(host_info_):
            return Result.fail_response(msg="执行失败(%s)" %ReturnClass.get_value(host_info_))

        #待更新环境标记服务器信息获取
        if not if_target_location:
            host_info_old_ = get_kubernetes_cluster_sign_info(old_kubernetes_cluster_id)
            if not ReturnClass.if_ok(host_info_old_):
                return Result.fail_response(msg="执行失败(%s)" % ReturnClass.get_value(host_info_old_))
            host_info_old = ReturnClass.get_value(host_info_old_)

        #根据运行时查询打包命令
        host_info = ReturnClass.get_value(host_info_)
        if host_info['kubernetes_runtime']:
            cmd_info = quit_k8s_download_cmd(host_info['kubernetes_runtime'])
        else:
            return Result.fail_response(msg="执行失败(集群运行时信息未维护.)")

        deploy_event_ids = str(uuid.uuid1())
        cmd_template_swap_value = {
            "images_tar": str(uuid.uuid1()),
            "namespace": data['now_version_cluster_select_value'],
            "images_shell_list": ' '.join(get_ready_images_list)
        }

        host_tar_path = ""
        conf_obj = Configuration()
        # 替换模板命令的模板内容
        for cmd_info_one  in cmd_info:
            cmd_info_one['system_content'] = conf_obj.replace_text_parameter(cmd_info_one['system_content'],
                                                                           cmd_template_swap_value)
            if cmd_info_one['assistant_information_1']:
                host_tar_path = conf_obj.replace_text_parameter(cmd_info_one['assistant_information_1'],
                                                                                 cmd_template_swap_value)

        download_event_in(deploy_event_ids, '信息处理完成', '1', download_enent_step_code=0)

        p = threading.Thread(target=start_down, args=(
            host_info, cmd_info, deploy_event_ids, 1, host_tar_path, host_info_old, if_target_location))
        p.start()

        return Result.success_response(data=deploy_event_ids, msg='执行成功,开始获取过程信息')

# 下载异步进程动作
def start_down(host_info, cmd_info, deploy_event_ids, start_download_enent_step_code, host_tar_path, host_info_old, if_target_location):
    deploy_k8s = SshExec(host_info, deploy_event_ids)
    deploy_k8s.set_ssh()
    start_download_enent_step_code = deploy_k8s.host_action_execute(cmd_info, start_download_enent_step_code)
    if host_tar_path:
        local_file_path = settings.APP_CONF['TMPPATH']
        start_download_enent_step_code = deploy_k8s.get_file(host_tar_path, local_file_path, 'images_down', start_download_enent_step_code)
    else:
        download_event_in(deploy_event_ids, '下载文件目录模板不存在，请检查数据库命令模板（system_action：tar_image：assistant_information_1）', '0', start_download_enent_step_code)
        return False
    deploy_k8s.ssh_close()

    if not if_target_location:
        file_name = os.path.basename(host_tar_path)
        local_path = os.path.join(local_file_path, 'images_down', file_name)

        push_hots_obj = SshExec(host_info_old, deploy_event_ids)
        push_hots_obj.set_ssh()

        exec_copy_ = threading.Thread(target=push_hots_obj.put_file_image, args=(local_path, start_download_enent_step_code))
        exec_copy_.start()

        push_hots_obj.put_file_image_progress(start_download_enent_step_code)

        push_hots_obj.ssh_close()

    return True